/**
 * 封装对单个图片、多个图片等的封装
 *
 *--------------------------------------
 * 图片字段域的封装
 * -----------------------------------
 * @desc 图片字段域 增加form-upload-image类
 * @attr 属性：data-field 字段名称 data-mode 模式1单图2多图 data-src 图片源(多图模式下各图片使用"|"分割)
 * @example 例如:
 * <div class="layui-input-inline form-upload-image" data-field="avatar" data-mode="1" data-src=""></div>
 */

layui.define(['jquery', 'uploadFile','layer'], function (exports) {
    var $ = layui.$,
        layer = layui.layer,
        uploadFile = layui.uploadFile;
    /**
     * 图片文件上传域初始化（多图及单图）
     */
    $(".form-upload-image").each(function (i, item) {
        var _this = $(item);
        var mode = _this.data('mode') || 1;
        var src = _this.data('src') || '';
        if (mode == 1) {
            var default_name = 'single_image_' + i;
        } else {
            var default_name = 'multi_image_' + i;
        }
        var field = _this.data('field') || default_name;
        if (mode == 1) {
            init_single_field(_this, field, src);
        } else if (mode == 2) {
            init_multi_field(_this, field, src);
        } else {
            console.log('图片初始化模式不支持');
        }
    })
    /**
     * 监控图片相关域中点击事件
     */
    $(document).on('click', '.btn-select-image', function () {
        var _parent_item = $(this).parents('.layui-form-item').eq(0);
        var mode = $(this).data('mode');
        var field = $(this).data('field');
        var size = $(this).data('size') || 4096;
        if (mode == 1) {
            var number = 1;
        } else if (mode == 2) {
            var number = $(this).data('number') || 0;
        }
        var upload = uploadFile({
            title: '图片上传',
            number: number,
            size: size
        });
        upload.image(mode, function (imgs) {
            if (mode == 1) {
                $("input[name=" + field + "]").val(imgs[0]);
                $("#preview_" + field).attr('src', imgs[0]);
            } else if (mode == 2) {
                if(number>0){
                   var current_number =  _parent_item.next().find(".multi-item").length;
                   if(current_number>=number){
                        layer.msg('最多上传'+number+'张图片',{icon:5,time:1000});
                        return -1;
                   }
                }
                var current_number = 0;
                var _item_html = "";
                if (imgs.length > 0) {
                    for (var i = 0; i < imgs.length; i++) {
                        _item_html += create_mulit_item(field, imgs[i]);
                    }
                }
                var multi_datas = $("#" + field).parents('.layui-form-item').eq(0).next().find(".multi-datas");
                multi_datas.append(_item_html);
            }
        })
    }).on('click', '.layui-close', function () {
        var field = $(this).data('field');
        $("#" + field).val("");
        $("#preview_" + field).attr("src", "");
    }).on('click', '.layui-close-multi', function () {
        $(this).parents(".multi-item").eq(0).remove();
    })


    /**
     * 单个图片文件上传初始化html
     * @param _this
     */
    function init_single_field(_this, field, src) {
        var _html = "";
        var requied = _this.data('required') || false;
        var size = _this.data('size') || 4096;
        var extend_class = _this.data('extend-class') || '';
        var width = _this.data('width') || '';
        if(width>0){
            width = ' style="width:'+width+'px!important"';
        }
        _html += '<input type="text" name="' + field + '" '+width + ' value="' + src + '" id="' + field + '" '+(requied?'lay-verify="required"':'')+' class="layui-input-inline layui-input layui-disabled layui-bg-gray" />';
        _html += '<a href="javascript:;" data-mode="1" data-field="' + field + '" data-size="' + size + '" class="layui-btn layui-btn-primary btn-select-image" style="margin-left:-10px">选择图片</a>';
        _this.html(_html);
        //插入预览html
        var _preview_html = '<div class="layui-form-item '+extend_class+' " style="margin-top:.5em;">';
        _preview_html += ' <label class="layui-form-label"></label>';
        _preview_html += ' <div class="layui-input-inline">';
        _preview_html += '<img id="preview_' + field + '" src="' + src + '" onerror="this.src=\'/images/nopic.jpg\'; this.title=\'图片未找到.\'" class="img-thumbnail" style="width:150px;" >';
        _preview_html += '<em class="layui-close" data-field="' + field + '" style="position:absolute; top: 0px;" title="删除这张图片">×</em>';
        _preview_html += '</div>';
        _preview_html += '</div>';
        _this.parents(".layui-form-item").after(_preview_html);
    }

    /**
     * 多个图片文件上传初始化html
     * @param _this
     */
    function init_multi_field(_this, field, src) {
        var _html = "";
        var size = _this.data('size') || 4096;
        var number = _this.data('number') || 0;
        var width = _this.data('width') || '';
        if(width>0){
            width = ' style="width:'+width+'px"';
        }
        var extend_class = _this.data('extend-class') || '';
        _html += '<input type="text" '+width + ' placeholder="批量上传图片'+(number>0?'最多上传'+number+'张':'')+'" id="' + field + '"  class="layui-input-inline layui-input layui-disabled layui-bg-gray" />';
        _html += '<a href="javascript:;" data-mode="2" data-field="' + field + '" data-size="' + size + '" data-number="' + number + '" class="layui-btn layui-btn-primary btn-select-image" style="margin-left:-10px">选择图片</a>';
        _this.html(_html);
        //插入预览html
        if(src==''){
            var images = new Array();
        }else{
            var images = src.split('|');
        }
        var _item_html = "";
        var _preview_html = '<div class="layui-form-item '+extend_class+' multi-image-details">';
        _preview_html += '<label class="layui-form-label"></label>';
        _preview_html += '<div class="layui-input-block multi-datas">';
        if (images.length > 0) {
            for (var i = 0; i < images.length; i++) {
                _item_html += create_mulit_item(field, images[i]);
            }
        }
        _preview_html += _item_html + '</div>';
        _preview_html += '</div>';
        _this.parent().after(_preview_html);
    }

    /**
     * 多图片模式下每个图片的html
     */
    function create_mulit_item(field, img) {
        //插入预览html
        var _html = '<div class="multi-item">';
        _html += '<img onerror="this.src=\'/images/nopic.jpg\'; this.title=\'图片未找到.\'" src="' + img + '" class="img-responsive img-thumbnail">';
        _html += '<input type="hidden" name="' + field + '[]" value="' + img + '">';
        _html += '<em class="layui-close-multi" title="删除这张图片">×</em>';
        _html += '</div>';
        return _html;
    }

    /**
     * 初始化百度编辑器
     */
    var ueditor_options = {
        'elementPathEnabled': false,
        'initialFrameHeight': 200,
        'focus': false,
        'maximumWords': 9999999999999,
        'autoClearinitialContent': false,
        'toolbars': [['source', '|', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'backcolor', '|',
            'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion',
            'link', 'removeformat', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', 'indent', 'paragraph', 'fontsize', '|',
           'map']],
        autoHeightEnabled: false,//自动增高
        autoFloatEnabled: false,
    }
    if (typeof window.UE == 'undefined') {
    } else {
        UE.registerUI('button', function (editor, uiName) {
            //注册按钮执行时的command命令，使用命令默认就会带有回退操作
            editor.registerCommand(uiName, {
                execCommand: function () {
                    console.log(uiName);
                    // require(['bootstrap', 'fileUploader'], function ($, fileUploader) {
                    //     var opts = {
                    //         type: 'image',
                    //         multiple: true,
                    //         extensions: 'gif,jpg,jpeg,bmp,png',
                    //     };
                    //     fileUploader.show(function (imgs) {
                    //         if (imgs.length == 0) {
                    //             return;
                    //         } else {
                    //             var imglist = [];
                    //             for (i in imgs) {
                    //                 imglist.push({
                    //                     'src': imgs[i],
                    //                     'max-width': '100%',
                    //                 });
                    //             }
                    //             editor.execCommand('insertimage', imglist);
                    //         }
                    //     }, opts);
                    // });
                }
            });
            //创建一个button
            var btn = new UE.ui.Button({
                //按钮的名字
                name: uiName,
                //提示
                title: uiName,
                //添加额外样式，指定icon图标，这里默认使用一个重复的icon
                cssRules: 'background-position: -726px -77px',
                //点击时执行的命令
                onclick: function () {
                    //这里可以不用执行命令,做你自己的操作也可
                    editor.execCommand(uiName);
                }
            });
            //当点到编辑内容上时，按钮要做的状态反射
            editor.addListener('selectionchange', function () {
                var state = editor.queryCommandState(uiName);
                if (state == -1) {
                    btn.setDisabled(true);
                    btn.setChecked(false);
                } else {
                    btn.setDisabled(false);
                    btn.setChecked(state);
                }
            });
            //因为你是添加button,所以需要返回这个button
            return btn;
        }, 19);
        $('.form-editor').each(function (i, item) {
            var _this = $(item);
            var obj_id = _this.prop('id');
            if (obj_id == '') {
                return -1;
            }
            var ue = window.UE.getEditor(obj_id, ueditor_options);
        })
    }
    exports('formField', {});
});